/*
// C16购物车20151106
 */
$(function() {
    commTemplUtil.initPage();
    //初始化购物车列表
    getClassifyData(1);
    //输入框

});

//列表模板
var classifyTempl = _.template($('#cart-template').html());

//初始化购物车列表
function getClassifyData(page) {

    var defaultPagingObj = {
        total: 0,
        pageSize: 10,
        page: 1
    };

    PAGE_DATA.pagingObj = $.extend(defaultPagingObj, PAGE_DATA.pagingObj);

    var onClickObj = {
        onClick: function() {
            var clickPage = $(this).attr("data-page");
            getSettleAccountInfo(parseInt(clickPage));
        }
    };

    $.ajax({
        url: PAGE_CONFIG.requestUrl.queryGoodcart,
        type: "get",
        data: {
            page: page + "",
            pageSize: PAGE_DATA.pagingObj.pageSize
        },
        success: function(result) {
            //购物车总价
            $('#total').html("￥" + result.total);
            $('#total').attr("total", result.total);
            //响应
            setClassifyData('cart-line', result.data, classifyTempl);

            //  更新翻页控件
            var tmpConf = $.extend(result.pagingConfData, onClickObj)
            commTemplUtil.initPaging("#comm-paging", tmpConf);
        },
        error: function() {
            var conf = {
                title: "注意",
                message: "获取购物车信息失败!",
                ok_txt: "确定"
            };
            commTemplUtil.showErrorDialog(conf);
        }
    });
};

/**
 * 生成购物车列表,
 */
function setClassifyData(id, data, templ) {
    var classifyTemplHtml = templ(data);
    $("#" + id).html(classifyTemplHtml);
    bindEvents(templ);
    $("input").blur(function() {
        var getVal = $(this).val();
        $(this).attr("value", getVal);
        countCartNum($(this).attr("code"), 0, getVal);

    });
};

/***
 * 页面填充数据后, 绑定事件;
 */
function bindEvents(htmlObj) {

    var commBody = $("#cart-line");

    var onClickObj = {
        onClick: function() {
            var clickPage = $(this).attr("data-page");
            getSettleAccountInfo(parseInt(clickPage));
        }
    };

    // 删除
    commBody.find(".btn-w90x33").on("click", function() {
        var id = $(this).parents("ul").attr("data-id");

        //确认框模板
        var confirmObj1 = _.template($('#item-confirm').html());
        var dia = dialog({
            title: '注意',
            content: confirmObj1
        });
        dia.showModal();

        $("#tj").on("click", function(event) {
            $.ajax({
                url: PAGE_CONFIG.requestUrl.delGoodCart,
                type: "delete",
                data: {
                    goodid: id, //商品id
                    _token: COMM_DATA.csrfToken
                },
                success: function(result) {
                    //响应
                    setClassifyData('cart-line', result.data, classifyTempl);
                    dia.remove();

                    //  更新翻页控件
                    var tmpConf = $.extend(result.pagingConfData, onClickObj)
                    commTemplUtil.initPaging("#comm-paging", tmpConf);
                },
                error: function() {
                    dia.remove();

                    var conf = {
                        title: "注意",
                        message: "删除商品失败!",
                        ok_txt: "确定"
                    };
                    commTemplUtil.showErrorDialog(conf);
                }
            });
        });
        $(".remove").click(function() {
            dia.remove();
        });
    });

    // 收藏
    commBody.find(".btn-w90x32").on("click", function() {
        var id = $(this).parents("ul").attr("data-id");

        //确认框模板
        var confirmObj1 = _.template($('#sc-confirm').html());
        var dia = dialog({
            title: '注意',
            content: confirmObj1
        });
        dia.showModal();

        $("#tj").on("click", function(event) {
            $.ajax({
                url: PAGE_CONFIG.requestUrl.collectGood,
                type: "put",
                data: {
                    goodid: id, //商品id
                    _token: COMM_DATA.csrfToken
                },
                success: function(result) {
                    //响应
                    setClassifyData('cart-line', result.data, classifyTempl);
                    dia.remove();

                    //  更新翻页控件
                    var tmpConf = $.extend(result.pagingConfData, onClickObj)
                    commTemplUtil.initPaging("#comm-paging", tmpConf);
                },
                error: function() {
                    dia.remove();

                    var conf = {
                        title: "注意",
                        message: "收藏商品失败!",
                        ok_txt: "确定"
                    };
                    commTemplUtil.showErrorDialog(conf);
                }
            });
        });
        $(".remove").click(function() {
            dia.remove();
        });
    });
}

/**
 * 购物车中商品数量加、减
 * goodid 购物车中的商品id
 * num 数量，加：1；减：-1 不操作：0
 */
function countCartNum(goodid, num, buy_num) {

    var defaultPagingObj = {
        total: 0,
        pageSize: 10,
        page: 1
    };

    PAGE_DATA.pagingObj = $.extend(defaultPagingObj, PAGE_DATA.pagingObj);

    var onClickObj = {
        onClick: function() {
            var clickPage = $(this).attr("data-page");
            getSettleAccountInfo(parseInt(clickPage));
        }
    };
    // var getBuynum = $(this).val();
    // alert(getBuynum);
    //购物车加减数量请求后台
    $.ajax({
        url: PAGE_CONFIG.requestUrl.countGoodcart,
        type: "put",
        data: {
            goodid: goodid, //购物车中商品id
            num: num, //数量加为1，减为-1
            buy_num: buy_num, //购买数量
            page: defaultPagingObj.page + "",
            pageSize: PAGE_DATA.pagingObj.pageSize,
            _token: COMM_DATA.csrfToken
        },
        success: function(result) {
            //购物车总价
            $('#total').html("￥" + result.total);
            $('#total').attr("total", result.total);
            //响应
            setClassifyData('cart-line', result.data, classifyTempl);

            //  更新翻页控件
            var tmpConf = $.extend(result.pagingConfData, onClickObj)
            commTemplUtil.initPaging("#comm-paging", tmpConf);
        },
        error: function() {
            var conf = {
                title: "注意",
                message: "获取购物车信息失败!",
                ok_txt: "确定"
            };
            commTemplUtil.showErrorDialog(conf);
        }
    });

    //TODO===================以下注释代码为客户端加减数量时判定金额，如果采用现在这种ajax刷新页面就用不着了
    //判断商品数量大于0时才可以减，否则默认为0
    //  var tempNum = $('#num_'+goodid).val();
    //  if($('#num_'+goodid).val() > 1 || num != -1){
    //      $('#num_'+goodid).val(add($('#num_'+goodid).val(),num));
    //  }else{
    //      $('#num_'+goodid).val(1);
    //  }
    //
    //  //==========计算小计
    //  //得到单价
    //  var price = $('#price_'+goodid).attr("price");
    //  //得到数量
    //  var count = $('#num_'+goodid).val();
    //  //小计
    //  var subtotal = mul(price,count);
    //  $('#sub_'+goodid).html("￥"+subtotal);
    //
    //  var total = $('#total').attr("total");
    //  //================计算购物车总价====加数量时tempNum大于0即可，减数量时tempNum必须大于1
    //  if(tempNum > 0 && num == 1){
    //      //购物车总价
    //      $('#total').html("￥"+add(total,price));
    //      $('#total').attr("total",add(total,price));
    //  }else if(tempNum > 1 && num == -1){
    //      //购物车总价
    //      $('#total').html("￥"+sub(total,price));
    //      $('#total').attr("total",sub(total,price));
    //  }
};

//加
function add(a, b) {
    var c,
        d,
        e;
    try {
        c = a.toString().split(".")[1].length;
    } catch (f) {
        c = 0;
    }
    try {
        d = b.toString().split(".")[1].length;
    } catch (f) {
        d = 0;
    }
    return e = Math.pow(10, Math.max(c, d)), (mul(a, e) + mul(b, e)) / e;
}
//减
function sub(a, b) {
    var c,
        d,
        e;
    try {
        c = a.toString().split(".")[1].length;
    } catch (f) {
        c = 0;
    }
    try {
        d = b.toString().split(".")[1].length;
    } catch (f) {
        d = 0;
    }
    return e = Math.pow(10, Math.max(c, d)), (mul(a, e) - mul(b, e)) / e;
}
//乘
function mul(a, b) {
    var c = 0,
        d = a.toString(),
        e = b.toString();
    try {
        c += d.split(".")[1].length;
    } catch (f) {}
    try {
        c += e.split(".")[1].length;
    } catch (f) {}
    return Number(d.replace(".", "")) * Number(e.replace(".", "")) / Math.pow(10, c);
}
//除
function div(a, b) {
    var c,
        d,
        e = 0,
        f = 0;
    try {
        e = a.toString().split(".")[1].length;
    } catch (g) {}
    try {
        f = b.toString().split(".")[1].length;
    } catch (g) {}
    return c = Number(a.toString().replace(".", "")),
        d = Number(b.toString().replace(".", "")),
        mul(c / d, Math.pow(10, f - e));
}
